# coding:utf-8
import re
from socket import *
from multiprocessing import Process

HTML_ROOT_DIR = "./html"
def handleClient(clientSocket):
    recvData = clientSocket.recv(1024)
    print(recvData)
    recvLines = recvData.splitlines()

    response_start_line = recvLines[0]
    fileName = re.match(r"\w+\s+(/[^ ]*)",recvLines[0].decode("utf-8")).group(1)
    if fileName == '/':
        fileName = "/index.html"
    try:
        file = open(HTML_ROOT_DIR+fileName,"rb")
    except IOError:
        response_start_line = "HTTP/1.1 404 Not Found\r\n"
        response_headers = "Server: My server\r\n"
        response_body = "file is not found"
    else:
        fileData = file.read()
        file.close()

        response_start_line = "HTTP/1.1 200 ok\r\n"
        response_headers = "Server: My server\r\n"
        response_body = fileData.decode("utf-8")

    sendData = response_start_line + response_headers + "\r\n" + response_body
    clientSocket.send(bytes(sendData, "utf-8"))
    clientSocket.close()

if __name__ == "__main__":
    serSocket = socket(AF_INET, SOCK_STREAM)
    serSocket.bind(("", 8000))
    # serSocket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    serSocket.listen(128)
    while True:
        clientSocket, clientAddr = serSocket.accept()
        print(str(clientAddr), "连上了")
        cProcess = Process(target=handleClient, args=(clientSocket,))
        cProcess.start()
        clientSocket.close()
